package com.sky.moduels.mini.controller;

import com.sky.moduels.mini.service.WxMessageService;
import com.sky.moduels.mini.wx.mp.constants.BaseConstant;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.mp.api.WxMpService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @Description: 微信消息Controller
 * @ClassName: MiniMessageController
 * @Author: hupengming
 * @CreateTime: 2022-08-19 10:01
 */
@Slf4j
@RestController
@RequestMapping("/wx")
public class MiniMessageController {

    @Autowired
    WxMpService wxMpService;

    @Autowired
    WxMessageService wxMessageService;

    /**
     * 接收验证消息，（验证消息的确来自微信服务器）
     *
     * @param timeStamp 时间戳
     * @param nonce 随机数
     * @param signature 微信加密签名
     * @param echostr 随机字符串。
     * @return 验证正确后将echostr原样返回
     */
    @GetMapping("/message")
    public String checkMessage(@RequestParam(name = "timestamp") String timeStamp,
                               @RequestParam(name = "nonce") String nonce,
                               @RequestParam(name = "signature") String signature,
                               @RequestParam(name = "echostr") String echostr) {
        log.info("【开始验证】");
        if(StringUtils.isAnyEmpty(timeStamp,nonce,signature,echostr)){
            log.info("【请求参数不正确】-【timeStamp】:{}-【nonce】:{}-【signature】:{}-【echostr】:{}",timeStamp,nonce,signature,echostr);
            return BaseConstant.ERROR_STR;
        }
        boolean b = wxMpService.checkSignature(timeStamp, nonce, signature);
        if (b) {
            return echostr;
        }
        return BaseConstant.ERROR_STR;
    }

    /**
     * 微信消息
     *
     * @param request
     * @throws IOException
     */
    @PostMapping("/message")
    public String wxMessage(HttpServletRequest request) throws IOException {
        return wxMessageService.pullWxMessage(request);
    }


}
